package flights.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import flights.bi.Admin;
import flights.bi.Airline;
import flights.bi.User;
import flights.db.AdminHandler;
import flights.db.AirlineHandler;
import flights.db.UserHandler;

/**
 * Servlet implementation class CookieServlet
 */
public class CookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType( "text/html" ); 
		Cookie[] cookies = request.getCookies();
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
		String type = "";
		String id = "";
		
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				switch (cookie.getName()) {
				case "UserType":
					type = cookie.getValue();
					break;
				case "UserID":
					id = cookie.getValue();
					break;
				}
			}
		}
		
		try
		{
			switch (type) {
			case "member":
				User user = UserHandler.getUserByID(Integer.parseInt(id));
				out.write(gson.toJson(user));
				break;
	
			case "airline":
				Airline air = AirlineHandler.getAirlineById(id);
				out.write(gson.toJson(air));
				break;
			case "admin":
				Admin admin = AdminHandler.getUserByID(Integer.parseInt(id));
				out.write(gson.toJson(admin));
				break;
				default :
					out.write("{}");
			}
		}
		catch (SQLException e)
		{
			out.write(e.getMessage());
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
